package cn.edu.sjtu.stap.util;

import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.asm.*;

public class Utils {
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");
    
    public static int comparePrecedence(AdviceDeclaration a1,
            AdviceDeclaration a2) {
        AstAsmMap map = AstAsmMap.getInstance();
        IProgramElement pe1 = map.get(a1);
        IProgramElement pe2 = map.get(a2);
        String s1 = pe1.getHandleIdentifier(true);
        String s2 = pe2.getHandleIdentifier(true);
        // System.err.println(s1 + ", " + s2);
        // System.err.flush();
        int i1 = getCount(s1);
        int i2 = getCount(s2);
        int k1 = getKind(s1);
        int k2 = getKind(s2);
        if (k1 == 3 || k2 == 3) { // If either is after.
            return i2 - i1; // If i2 appear later than i1, i2 has higher
            // precedence, and should be put behind i1.
        }
        return i1 - i2; // If neither is after, the one appear earlier has
        // higher precedence, and should be put forward the other.
    }

    private static int getCount(String handler) {
        int place = handler.lastIndexOf('!');
        String count = handler.substring(place + 1);
        // System.err.println(count);
        int result = 0;
        try {
            result = Integer.parseInt(count);
        } catch (Throwable t) {
            return 1;
        }
        return result;
    }

    private static int getKind(String handler) {
        if (handler.contains("&before")) {
            return 1;
        } else if (handler.contains("&around")) {
            return 2;
        } else if (handler.contains("&after")) {
            return 3;
        } else {
            throw new IllegalArgumentException("Error handler!");
        }
    }
}
